package net.loyintean.pearlshell.validation.util;

import com.sinoisg.pearlshell.base.model.IResult;
import com.sinoisg.pearlshell.base.model.impl.ResultFactory;
import net.loyintean.pearlshell.validation.IValidField;
import net.loyintean.pearlshell.validation.IValidRule;
import net.loyintean.pearlshell.validation.IValidRuleConfig;
import net.loyintean.pearlshell.validation.rule.IValidFactory;
/**
 * 对输入的内容进行校验
 * @author linjun-ghq
 * 
 */
public class ValidUtil {

	private static final String SUCCESS = "校验通过";

	private static final IValidFactory FACTORY = IValidFactory.SINGLETON_FACTORY;

	private static final String valid(Object toValid,
			IValidRuleConfig... ruleConfigList) {
		assert ruleConfigList != null;

		for (int configIndex = 0; configIndex < ruleConfigList.length; configIndex++) {

			IValidRuleConfig config = ruleConfigList[configIndex];

			IValidRule rule = FACTORY.buildRule(config);

			assert rule != null;

			if (!rule.valid(toValid, config)) {

				return rule.errorMsg(config);

			}

		}

		return SUCCESS;
	}

	public static final IResult<String> valid(IValidField... fields) {
		assert fields != null;

		IResult<String> result = ResultFactory.INIT();

		result.success(SUCCESS);

		String fieldResult = null;

		for (IValidField field : fields) {

			fieldResult = valid(field.value(), field.configs());

			if (!SUCCESS.equals(fieldResult)) {

				result.fail(field.name() + fieldResult);

				break;
			}
		}

		return result;

	}
}
